package com.athuawei.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock是一个接口，
 * Lock在发生异常时，不使用unlock无法释放锁～
 *
 * ====== 多线程编程中部：
 * 1.线程间通信
 *  ReentrantLock
 *  非公平锁：有线程饿死现象；
 * 2.可重入锁
 *  synchronized（隐式）和Lock（显式）都是可重入锁；
 */
class LTiket {
    private int number = 30;

    // 创建可重入锁
    private final ReentrantLock lock = new ReentrantLock(true);

    // 卖票方法
    public void sale() {
        //上锁
        lock.lock();

        try {
            if(number > 0) {
                System.out.println(Thread.currentThread().getName() +
                        " : 卖出：" + number-- + "剩余：" + number);
            }
        } finally {
            //释放锁
            lock.unlock();
        }
    }
}

public class LSaleTicket {



    public static void main(String[] args) {

        LTiket ticket = new LTiket();
        new Thread(()->{
           for (int i = 0; i < 40; i++) {
               ticket.sale();
           }
        }, "AA").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "BB").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "CC").start();
    }

}
